<?php

/*
 * json数据转为sql脚本
  ('350000','福建省','35','00','00','1');
  ('350600','漳州市','35','06','00','2')
  ('350681','龙海市','35','06','81','3');
  省份：where level=1
  城市：where sheng='35' and level=2
  地区：where sheng='35' and di='06' and level=3
 * @version 2017-4-12 added.
 * @version 2018-1-29 重构，新增输出到文件的方法
 */

/**
 * 转换省市区数据
 * @version 2017-4-12
 */
function convertAreaData() {
// code,sheng,di,xian,name,level
    $str = file_get_contents('shengdixian.txt');
    $arr = [];
    if ($str) {
        $arr = json_decode($str, true);
    }
    if(!$arr){
        exit('none data');
    }
    $writefile=true;
    if ($writefile) {
        // 写入文件
        if ($fp = fopen('./sql_number_regional.sql', 'a')) {
            foreach ($arr as $row) {
                $content = "insert into t_common_area (code, name, pid, cid, aid, level) values ('" . $row['code'] . "','" . $row['name'] . "','" . $row['sheng'] . "','" . $row['di'] . "','" . $row['xian'] . "','" . $row['level'] . "');".PHP_EOL;
                fwrite($fp, $content);
            }
            fclose($fp);
        }
        echo 'success';
    } else {
        foreach ($arr as $row) {
            echo "insert into t_common_area (code, name, pid, cid, aid, level) values ('" . $row['code'] . "','" . $row['name'] . "','" . $row['sheng'] . "','" . $row['di'] . "','" . $row['xian'] . "','" . $row['level'] . "');<br />";
        }
    }
}

/**
 * 转换号段
 * @version 2018-1-29
 */
function convertNumberRegionData() {
    // 修改配置php.ini：memory_limit = 256M
    // 修改配置my.ini：group_concat_max_len = 10240000; 默认1K,需要10M=10000K
    // SELECT GROUP_CONCAT(CONCAT('{"na":"',area_name,'", "nu":"', segment_number,'"}')) FROM `t_common_number_regional`;
    $str = file_get_contents('number_regional.txt');
    $arr = [];
    if ($str) {
        $arr = json_decode($str, true);
    }
    if(!$arr){
        exit('none data');
    }
    $writefile=true;
    if ($writefile) {
        // 写入文件
        if ($fp = fopen('./sql_number_regional.sql', 'a')) {
            foreach ($arr as $row) {
                $content = "insert into t_common_number_regional (area_name, segment_number) values ('" . $row['na'] . "','" . $row['nu'] . "');".PHP_EOL;
                fwrite($fp, $content);
            }
            fclose($fp);
        }
        echo 'success';
    } else {
        foreach ($arr as $row) {
            echo "insert into t_common_number_regional (area_name, segment_number) values ('" . $row['na'] . "','" . $row['nu'] . "');<br />";
        }
    }
}

convertNumberRegionData();
